package com.baijia.authentication.handler.support;

import com.baijia.authentication.handler.NamedAuthenticationHandler;
import com.baijia.authentication.handler.exception.AuthenticationException;
import com.baijia.authentication.principal.Credentials;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

/**
 * @title AbstractPreAndPostProcessingAuthenticationHandler
 * @desc 认证前后可以做一些事情
 * @author caoliang
 * @date 2015年12月4日
 * @version 1.0
 */
public abstract class AbstractPreAndPostProcessingAuthenticationHandler implements NamedAuthenticationHandler {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${passport.for_test:false}")
    protected boolean test;//是否是测试环境，测试环境使用固定的验证码即给登录
    
    private static final String TEST_PASSWD = "111111";
    
    private String name = getClass().getName();

    /**
     * 认证前做一些工作
     * 
     * @param 登录凭证
     * @return 继续认证返回true，否则false
     */
    protected boolean preAuthenticate(final Credentials credentials) throws AuthenticationException {
        return true;
    }

    /**
     * 认证后做一些工作
     * 
     * @param 登录凭证
     * @param 认证结果
     * @return 根据实际情况，是否返回认证成功
     */
    protected boolean postAuthenticate(final Credentials credentials, final boolean authenticated)
        throws AuthenticationException {
        return authenticated;
    }

    public final void setName(final String name) {
        this.name = name;
    }

    @Override
    public final String getName() {
        return this.name;
    }

    @Override
    public final boolean authenticate(final Credentials credentials) throws AuthenticationException {

        if (!preAuthenticate(credentials)) {
            return false;
        }

        final boolean authenticated = doAuthentication(credentials);

        return postAuthenticate(credentials, authenticated);
    }

    protected abstract boolean doAuthentication(final Credentials credentials) throws AuthenticationException;
    
    /**
     * 测试环境登录，为简化，密码固定为111111即可登录测试环境
     * @return
     */
    protected boolean testLogin(String password){
        return test && TEST_PASSWD.equals(password);
    }
}
